<template>
  <common-page class="add-view-board" :title="title">
    <el-button slot="header" @click="goBack">返回</el-button>
    <div class="choose-users-form" slot="content">
      <common-tabs slot="tabs" v-model="activeName" @tab-click="changeTabs">
        <el-tab-pane label="未选择人员" name="unselected"></el-tab-pane>
        <el-tab-pane label="已选择人员" name="selected"></el-tab-pane>
      </common-tabs>

      <div class="tabs-content">
        <!-- 未选择 -->
        <div class="dep-tree" v-loading="treeLoading">
          <common-tree
            slot="group"
            :isRequest="isRequest"
            :treeData="deptSelect"
            :treeProp="treeProp"
            :isShowFilter="false"
            is-slot
            @handleNodeClick="handleNodeClick"
          >
            <div
              style="width: 100%"
              slot-scope="{ scope }"
              :class="{ 'e-t-content': !scope.data.freeze }"
            >
              <common-carousel-text
                :content="scope.node.label"
                :index="scope.node.id"
                :font-size="14"
              >
              </common-carousel-text>
            </div>
          </common-tree>
        </div>
        <div class="user-list" v-if="activeName === 'unselected'">
          <common-search
            slot="search"
            @search="handleQuery"
            @reset="resetQuery"
          >
            <el-form
              @submit.native.prevent
              :model="query"
              ref="queryForm"
              v-show="true"
              :inline="true"
              label-width="47px"
            >
              <el-form-item label="用户名">
                <common-input
                  v-model="query.userName"
                  clearable
                  @enter="handleQuery"
                />
              </el-form-item>
            </el-form>
          </common-search>
          <div class="u-l-l-btn" slot="content">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              @click="handleBinding"
              data-test="user-add"
              :disabled="ids && ids.length === 0"
              >批量绑定
            </el-button>
          </div>
          <div class="u-l-l" v-loading="tableLoading" slot="content">
            <common-table
              slot="content"
              ref="userList"
              :data="unSelectedUsersList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="用户名" align="left" prop="userName" />
              <el-table-column label="姓名" align="left" prop="nickName" />
              <el-table-column label="操作" align="left" width="50">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleBinding(scope.row)"
                    >绑定</el-button
                  >
                </template>
              </el-table-column>
            </common-table>
          </div>
          <pagination
            slot="pagination"
            v-show="total > 0"
            :total="total"
            :page.sync="query.pageNum"
            :limit.sync="query.pageSize"
            @pagination="getUnSelectedUsers"
          />
        </div>

        <!-- 已选择 -->
        <div class="user-list" v-else>
          <common-search
            slot="search"
            @search="handleQuery"
            @reset="resetQuery"
          >
            <el-form
              @submit.native.prevent
              :model="querySelect"
              ref="queryForm"
              v-show="true"
              :inline="true"
              label-width="47px"
            >
              <el-form-item label="用户名">
                <common-input
                  v-model="querySelect.userName"
                  clearable
                  @enter="handleQuery"
                />
              </el-form-item>
            </el-form>
          </common-search>
          <div class="u-l-l-btn" slot="content">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              @click="deleteUser"
              data-test="user-add"
              :disabled="ids && ids.length === 0"
              >批量解绑
            </el-button>
          </div>
          <div class="u-l-l" v-loading="selectLoading" slot="content">
            <common-table
              slot="content"
              ref="userList"
              :data="selectedUsersList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="用户名" align="left" prop="userName" />
              <el-table-column label="姓名" align="left" prop="nickName" />
              <el-table-column label="操作" align="left" width="50">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    style="color: #f56c6c"
                    @click="deleteUser(scope.row)"
                    >解绑</el-button
                  >
                </template>
              </el-table-column>
            </common-table>
          </div>
          <pagination
            slot="pagination"
            v-show="selectDataTotal > 0"
            :total="selectDataTotal"
            :page.sync="querySelect.pageNum"
            :limit.sync="querySelect.pageSize"
            @pagination="getSelectedUsers"
          />
        </div>
      </div>
    </div>
  </common-page>
</template>

<script>
import {
  user_list,
  dept_select,
  batchAddUserPermission,
  batchDeleteUserPermission,
  batchAddUserRole,
  batchDeleteUserRole,
} from "@/api/management/usercenter/user.js";
import BaseList from "@/mixins/BaseList";
import {
  selectUsersByPermissionIds,
  selectUsersUnBindPermission,
  selectBindedUsersByRoles,
  selectUsersUnBindRole,
} from "@/api/system/user";

export default {
  name: "index",
  mixins: [BaseList],
  props: {
    type: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      activeName: "unselected",
      id: "",
      title: "",
      selectUserDialog: false,
      selectedUsersList: [],
      unSelectedUsersList: [],
      isEdit: false,
      loading: false,
      deptSelect: [], // 菜单树
      treeProp: {
        // 树参数
        children: "children",
        label: "label",
      },
      ids: [],
      isRequest: false,
      treeLoading: false,
      tableLoading: false,
      query: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        deptId: null, //部门id
      }, // 已选人员查询条件
      querySelect: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        deptId: null, //部门id
      }, // 未选人员查询条件
      total: 1,
      selectDataTotal: 1,
      selectLoading: false,
      key: "userId",
    };
  },
  methods: {
    cancel() {
      this.selectUserDialog = false;
    },
    goBack() {
      this.$emit("close");
    },
    changeTabs() {
      this.ids = [];
      this.getDeptSelect();
      if (this.activeName === "unselected") {
        this.getUnSelectedUsers();
      } else {
        this.getSelectedUsers();
      }
    },
    show(data) {
      // console.log(data)
      this.id =
        this.type === "role" && data.roleId
          ? data.roleId
          : this.type === "permission" && data.permissionId
          ? data.permissionId
          : "";

      let title =
        this.type === "role" && data.roleName
          ? data.roleName
          : this.type === "permission" && data.permissionName
          ? data.permissionName
          : "";

      this.title = title + "-人员设置";
      this.query.pageNum = 1;
      this.query.pageSize = 10;
      this.query.userName = null;
      this.querySelect.pageNum = 1;
      this.querySelect.pageSize = 10;
      this.querySelect.userName = null;

      this.getSelectedUsers();
      this.getUnSelectedUsers();
    },
    /**
     * 获取菜单树
     */
    getDeptSelect() {
      dept_select({})
        .then((res) => {
          if (res && res.code === 200) {
            this.deptSelect = res.data;
          } else {
          }
        })
        .catch((err) => {})
        .finally(() => (this.treeLoading = false));
    },
    /**
     * 点击菜单获取数据
     */
    handleNodeClick(data) {
      if (!!data.data.freeze) {
        if (this.activeName === "unselected") {
          this.query.pageNum = 1;
          this.query.pageSize = 10;
          this.query.deptId = data.data.id;
          this.query.userName = null;
          this.getUnSelectedUsers();
        } else {
          this.querySelect.pageNum = 1;
          this.querySelect.pageSize = 10;
          this.querySelect.deptId = data.data.id;
          this.querySelect.userName = null;
          this.getSelectedUsers();
        }
      }
    },
    /**
     * 所有人员筛选
     */
    handleQuery() {
      this.query.pageNum = 1;
      if (this.activeName === "unselected") {
        this.getUnSelectedUsers();
      } else {
        this.getSelectedUsers();
      }
    },

    resetQuery() {
      this.query.pageNum = 1;
      this.query.pageSize = 10;
      this.query.userName = null;
      this.querySelect.pageNum = 1;
      this.querySelect.pageSize = 10;
      this.querySelect.userName = null;
    },
    /**
     * 解绑人员
     * @param row
     */
    deleteUser(row) {
      let params = {
        userIds: row?.userId || this.ids.join(","),
      };
      this.$GlobalDeleteConfirm("是否确认解绑?")
        .then(() => {
          if (this.type === "role") {
            //角色
            params.roleId = this.id;
            batchDeleteUserRole(params).then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("解绑成功");
                this.getSelectedUsers();
              } else {
                this.$GlobalErrorConfirm("解绑失败", res.msg).then();
              }
            });
          } else {
            //数据权限
            params.permissionId = this.id;
            batchDeleteUserPermission(params).then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("解绑成功");
                this.getSelectedUsers();
              } else {
                this.$GlobalErrorConfirm("解绑失败", res.msg).then();
              }
            });
          }
        })
        .catch(() => {});
    },
    handleBinding(row) {
      let params = {
        userIds: row?.userId || this.ids.join(","),
      };
      if (this.type === "role") {
        //角色
        params.roleId = this.id;
        batchAddUserRole(params).then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("绑定成功");
            this.getUnSelectedUsers();
          } else {
            this.$GlobalErrorConfirm("绑定失败", res.msg).then();
          }
        });
      } else {
        //数据权限
        params.permissionId = this.id;
        batchAddUserPermission(params).then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("绑定成功");
            this.getUnSelectedUsers();
          } else {
            this.$GlobalErrorConfirm("绑定失败", res.msg).then();
          }
        });
      }
      this.$emit("bingUser", params);
    },
    /**
     * 获取已选人员
     */
    getSelectedUsers() {
      let params = {
        ...this.querySelect,
      };
      if (this.type === "permission") {
        params.permissionIds = [this.id];
        this.selectUsersByPermissionIds(params);
      } else {
        params.roleIds = [this.id];
        this.getSelectUsersByRoles(params);
      }
    },
    /**
     * 获取未选人员
     */
    getUnSelectedUsers() {
      let params = {
        ...this.query,
      };
      if (this.type === "permission") {
        params.permissionIds = [this.id];
        this.selectUsersUnBindPermission(params);
      } else {
        params.roleIds = [this.id];
        this.getSelectUsersUnBindRole(params);
      }
    },
    /**
     * 获取权限未选人员
     */
    selectUsersUnBindPermission(params) {
      selectUsersUnBindPermission(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.unSelectedUsersList = res.rows;
            this.total = res.total;
          } else {
            this.$GlobalErrorConfirm(
              "获取未选人员信息失败",
              res.msg,
              "重新加载"
            ).then(() => {
              this.selectUsersUnBindPermission(params);
            });
            this.handleListTips(res);
          }
        })
        .finally(() => {});
    },
    /**
     * 获取权限已选人员
     */
    selectUsersByPermissionIds(params) {
      selectUsersByPermissionIds(params).then((res) => {
        if (res && res.code === 200) {
          this.selectedUsersList = res.rows;
          this.selectDataTotal = res.total;
        } else {
          this.$GlobalErrorConfirm(
            "获取已选人员信息失败",
            res.msg,
            "重新加载"
          ).then(() => {
            this.getSelectedUsers(params);
          });
          this.handleListTips(res);
        }
      });
    },
    /**
     * 获取角色未选人员
     */
    getSelectUsersUnBindRole(params) {
      this.isRequest = true;
      selectUsersUnBindRole(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.unSelectedUsersList = res.rows;
            this.total = res.total;
          } else {
            this.$GlobalErrorConfirm(
              "获取未选人员信息失败",
              res.msg,
              "重新加载"
            ).then(() => {
              this.getSelectUsersUnBindRole(params);
            });
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.isRequest = false;
        });
    },
    /**
     * 获取角色已选人员
     */
    getSelectUsersByRoles(params) {
      this.isRequest = true;
      selectBindedUsersByRoles(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.selectedUsersList = res.rows;
            this.selectDataTotal = res.total;
          } else {
            this.$GlobalErrorConfirm(
              "获取已选人员信息失败",
              res.msg,
              "重新加载"
            ).then(() => {
              this.getSelectUsersByRoles(params);
            });
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.isRequest = false;
        });
    },
  },
  mounted() {
    this.getDeptSelect();
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-tree {
  font-size: 14px;

  .e-t-content {
    width: 100%;

    &:hover {
      cursor: not-allowed;
    }
  }
}

.choose-users-form {
  width: 100%;
  height: 100%;
  padding: 0 20px;

  .tabs-content {
    width: 100%;
    height: calc(100% - 40px);
    box-sizing: border-box;
    display: flex;
  }

  .dep-tree {
    width: 200px;
    border-right: 1px solid #eee;
    height: 100%;
    overflow-y: scroll;
    box-sizing: border-box;
    padding-top: 12px;
  }

  .user-list {
    padding: 12px 0 12px 12px;
    width: calc(100% - 200px);
    font-size: 14px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
  }

  .u-l-delete {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 17px;

    .el-button {
      margin-left: 20px;
    }
  }

  .u-l-l {
    /*min-height: 250px;*/
    flex: 1;
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
  }
}
</style>
